package com.example.syyao.myapp.Personal;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.syyao.myapp.Adapter.NVAdapter;
import com.example.syyao.myapp.CircleImageView;
import com.example.syyao.myapp.MainActivity;
import com.example.syyao.myapp.R;
import com.example.syyao.myapp.Response.Get_response;
import com.example.syyao.myapp.Response.Get_response_List;
import com.example.syyao.myapp.Response.Image;
import com.example.syyao.myapp.Sign.Sign_in;
import com.example.syyao.myapp.WebContact.JsonUtil;
import com.example.syyao.myapp.WebContact.WebAccessTools;
import com.google.gson.Gson;

import org.w3c.dom.Text;

import java.lang.reflect.Field;
import java.util.*;

import static java.lang.Thread.sleep;

public class PersonalFragment extends Fragment {

    private ListView listView;
    private List<List<Image>> imagesList;
    List<Map<String, Object>> myinformation;
    private NVAdapter nvAdapter;
    private String[][] images = new String[][]{
            {"file:///android_asset/img2.jpg", "250", "250"}
            , {"http://img3.douban.com/view/photo/photo/public/p2249526036.jpg", "640", "960"}
            , {"file:///android_asset/img3.jpg", "250", "250"}
            , {"file:///android_asset/img4.jpg", "250", "250"}
            , {"file:///android_asset/img5.jpg", "250", "250"}
            , {"file:///android_asset/img6.jpg", "250", "250"}
            , {"file:///android_asset/img7.jpg", "250", "250"}
            , {"file:///android_asset/img8.jpg", "250", "250"}
            , {"http://img4.douban.com/view/photo/photo/public/p2252689992.jpg", "1280", "800"}
    };

    private String picurl;

    //个人中心——菜单按钮
    private Get_response personal_respinse;
    private Get_response_List Movement_response;
    private Button btn_heart;
    private Button btn_star;
    private Button btn_send;
    private Drawable icon_heart;
    private Drawable icon_star;
    private Drawable icon_send;
    private ImageView setting;
    //粉丝
    private TextView fans;
    //关注的人
    private TextView conner;
    //昵称
    private TextView nickname;
    //等级
    private TextView level;
    //头像
    private CircleImageView head_picture;
    //称号
    private TextView personal_title;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.personal_people, container, false);
        View view1 = inflater.inflate(R.layout.fragment_personal, container, false);

        btn_heart = view.findViewById(R.id.button_hreat);
        btn_star = view.findViewById(R.id.button_star);
        btn_send = view.findViewById(R.id.button_send);

        conner = view.findViewById(R.id.textView7);
        fans = view.findViewById(R.id.textView8);
        nickname = view.findViewById(R.id.personal_name);
        head_picture = view.findViewById(R.id.personal_head);
        level = view.findViewById(R.id.personal_lv);
        personal_title = view.findViewById(R.id.personal_title);
        setting = view.findViewById(R.id.setting);
        //菜单按钮--关注
        Drawable icon_heart = getResources().getDrawable(R.mipmap.personal_hreat);
        icon_heart.setBounds(0, 0, 110, 110);
        btn_heart.setCompoundDrawables(null, icon_heart, null, null);
        //菜单按钮--粉丝
        Drawable icon_star = getResources().getDrawable(R.mipmap.personal_star);
        icon_star.setBounds(0, 0, 110, 110);
        btn_star.setCompoundDrawables(null, icon_star, null, null);
        btn_star.setOnClickListener(new btn_fans_lis());

        //菜单按钮--发表
        Drawable icon_send = getResources().getDrawable(R.mipmap.personal_send);
        icon_send.setBounds(0, 0, 100, 100);
        btn_send.setCompoundDrawables(null, icon_send, null, null);
        btn_send.setOnClickListener(new btn_send_lis());
        //绑定监听者
        btn_heart.setOnClickListener(new btn_heart_lis());
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(MainActivity.PREFERENCE_NAME, MainActivity.MODE);
        boolean isLogin = sharedPreferences.getBoolean("isLogin", false);
        if (isLogin) {
            final String username = sharedPreferences.getString("username", "1");
            init(username);
            setting.setOnClickListener(new btn_setting());

            listView = (ListView) view1.findViewById(R.id.lv_main);


            initData(username);

            Map<String, Object> map = new HashMap<>();
            map.put("head_picture", "1");
            map.put("nickname", "1");
            map.put("time", "1");
            map.put("tagname", "1");
            myinformation = new ArrayList<>();
            myinformation.add(map);

            imagesList = new ArrayList<>();
            List<Image> list = new ArrayList<>();
            list.add(new Image("http://120.79.205.71/picture/pic1.jpg", 250, 250));
            imagesList.add(list);

            nvAdapter = new NVAdapter(getContext(), imagesList, myinformation);


            listView.setAdapter(nvAdapter);

            listView.addHeaderView(view);
        }

        return view1;
    }


    private void init(final String username) {
        new Thread(new Runnable() {

            @Override
            public void run() {
//                System.out.println(username);
                String webContent = WebAccessTools.Get_Personal_Information(username);
                System.out.println("web:" + webContent);
                personal_respinse = (Get_response) JsonUtil.jsonToObject(webContent,
                        Get_response.class);
                handler.sendEmptyMessage(0x123);
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (personal_respinse != null && personal_respinse.getMessage().equals("成功")) {
                Map<String, Object> map = new HashMap<String, Object>();
                try {
                    map = objectToMap(personal_respinse.getData());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

                String conners = "";
                if (personal_respinse.getData().get("conner_number") == null) {
                    conners = "0";
                } else {
                    conners = personal_respinse.getData().get("conner_number").toString();
                }
                conner.setText(conners);

                String fan = "";
                if (personal_respinse.getData().get("fans_number") == null) {
                    fan = "0";
                } else {
                    fan = personal_respinse.getData().get("fans_number").toString();
                }
                fans.setText(fan);

                Gson gson = new Gson();
                Map<String, Object> mapp = new HashMap<String, Object>();

                mapp = gson.fromJson(personal_respinse.getData().get("Information").toString(), mapp.getClass());
                picurl = "http://120.79.205.71/picture/" + mapp.get("head_picture").toString();
                RequestOptions options = new RequestOptions().placeholder(R.mipmap.login_pic);
                Glide.with(getContext()).asBitmap().load("http://120.79.205.71/picture/" + mapp.get("head_picture").toString()).apply(options).into(head_picture);
                nickname.setText(mapp.get("nickname").toString());
                level.setText("Lv" + mapp.get("levl").toString().substring(0, 1));
                if (level.getText().equals("Lv1")) {
                    personal_title.setText("小萌新");
                } else {
                    personal_title.setText("小贱人");
                }


            }
        }

        ;
    };

    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }

    private class btn_heart_lis implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), Personal_heart.class);
            startActivity(intent);
        }
    }

    private class btn_fans_lis implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), Personal_fans.class);
            startActivity(intent);
        }
    }

    private class btn_setting implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), Setting.class);
            intent.putExtra("nickname", nickname.getText());
            intent.putExtra("headpicture", picurl);
            startActivity(intent);
        }
    }

    private class btn_send_lis implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), Personal_send.class);
            startActivity(intent);
        }
    }

    private void initData(final String username) {
//        imagesList=new ArrayList<>();
////        //这里单独添加一条单条的测试数据，用来测试单张的时候横竖图片的效果
//        ArrayList<Image> singleList=new ArrayList<>();
//        singleList.add(new Image(images[8][0],Integer.parseInt(images[8][1]),Integer.parseInt(images[8][2])));
//        imagesList.add(singleList);
//        //从一到9生成9条朋友圈内容，分别是1~9张图片
//        for(int i=0;i<9;i++){
//            ArrayList<Image> itemList=new ArrayList<>();
//            for(int j=0;j<=i;j++){
//                itemList.add(new Image(images[j][0],Integer.parseInt(images[j][1]),Integer.parseInt(images[j][2])));
//            }
//            imagesList.add(itemList);
//        }


        new Thread(new Runnable() {

            @Override
            public void run() {
//                System.out.println(username);
                String webContent = WebAccessTools.Get_Personal_Movement(username);
                System.out.println("MOVEMENT:" + webContent);
                Movement_response = (Get_response_List) JsonUtil.jsonToObject(webContent,
                        Get_response_List.class);
                hand.sendEmptyMessage(0x123);
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    private Handler hand = new Handler() {
        public void handleMessage(android.os.Message msg) {
            imagesList = new ArrayList<>();
            myinformation = new ArrayList<>();
            if (Movement_response != null && Movement_response.getMessage().equals("成功")) {
                List<Map<String, Object>> temp = Movement_response.getData();
                myinformation = new ArrayList<>();
                System.out.println(temp);
                if (temp.size() == 0) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("head_picture", "");
                    map.put("nickname", "");
                    map.put("time", "");
                    map.put("tagname", "");
                    myinformation = new ArrayList<>();
                    myinformation.add(map);

                    imagesList = new ArrayList<>();
                    List<Image> list = new ArrayList<>();
                    list.add(new Image("http://120.79.205.71/picture/pic1.jpg"));
                    imagesList.add(list);
                } else {
                    for (int i = 0; i < temp.size(); i++) {
                        //     String str = temp.get(i).get("tagname").toString().substring(1,temp.get(0).get("tagname").toString().length()-1);
                        ArrayList<Image> singleList = new ArrayList<>();
                        if (temp.get(i).get("mypicture") == null) {
                            singleList.add(new Image("http://120.79.205.71/picture/pic1.jpg"));
                        } else {
                            System.out.println( temp.get(0).get("mypicture").toString());
                            String a=temp.get(0).get("mypicture").toString();

                            String picture = temp.get(i).get("mypicture").toString().substring(1, temp.get(i).get("mypicture").toString().length() - 1);
                            picture = picture.replace(" ", "");
                            String[] arr = picture.split(",");
                            List<String> itemlist = Arrays.asList(arr);

                            for (int j = 0; j < itemlist.size(); j++) {
                                singleList.add(new Image("http://120.79.205.71/picture/" + itemlist.get(j), 500, 500));
                            }
                        }
                        System.out.println("singls:" + singleList.size());
                        Map<String, Object> map = new HashMap<>();
                        map.put("nickname", Movement_response.getData().get(i).get("nickname").toString());
                        if (Movement_response.getData().get(i).get("time") == null) {
                            map.put("time", new Date());
                        } else {
                            map.put("time", Movement_response.getData().get(i).get("time").toString());
                        }
                        map.put("head_picture", Movement_response.getData().get(i).get("head_picture").toString());
                        if (Movement_response.getData().get(i).get("tagname") == null) {
                            map.put("tagname", "");
                        } else {
                            map.put("tagname", Movement_response.getData().get(i).get("tagname").toString());
                        }
                        myinformation.add(map);
                        imagesList.add(singleList);
                    }
                }
                nvAdapter.update(getContext(), imagesList, myinformation);


            }
        }

        ;
    };
}
